package com.abc.realm;

import com.abc.entity.User;
import com.abc.mapper.UserMapper;
import com.abc.service.ex.GlobalException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println("当前登录人"+user);
        //根据user查询拥有的权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permissions = new HashSet<>();
        if("0".equals(user.getShenfen())){
            permissions.add("/gly");
        }else if("1".equals(user.getShenfen())){
            permissions.add("/js");
        }else{
            permissions.add("/xs");
        }
        System.err.println(permissions);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        // 得到用户名
        String username = token.getUsername();
        // 根据用户名查询用户信息
        User user = userMapper.selectByUsername(username);

        if (user == null) {
            throw new GlobalException( "登录失败，用户不存在~");
        }
        String password = new String(token.getPassword());

        if (user.getPassword().equals(password)) {
            return new SimpleAuthenticationInfo(user, password, username);
        } else {
            throw new GlobalException("密码错误！");
        }
    }
}
